# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,execjs
from common.helper import Helper
from urllib.parse import urlencode

class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "华夏福重大疾病保障计划"

    # 生产产品数据
    def genProductInfo(self):

        plan = {

            "planA" :{

                "year": [str(i) for i in range(0, 41)],
                "gender":["M", "F"],
                "money": [str(i) + "0000" for i in range(5, 55, 5)],
                "interval":["0", "5", "10","15", "20"],
                "expire":["终身"]
            },
            "planB": {

                "year": [str(i) for i in range(41, 46)],
                "gender": ["M", "F"],
                "money": [str(i) + "0000" for i in range(5, 35, 5)],
                "interval": ["0", "5", "10","15", "20"],
                "expire": ["终身"]
            },
            "planC": {

                "year": [str(i) for i in range(46, 51)],
                "gender": ["M", "F"],
                "money": [str(i) + "0000" for i in range(5, 25, 5)],
                "interval": ["0", "5","10","15", "20"],
                "expire": ["终身"]
            },
            "planD": {

                "year": [str(i) for i in range(51, 56)],
                "gender": ["M", "F"],
                "money": [str(i) + "0000" for i in range(5, 15, 5)],
                "interval": ["0", "5", "10"],
                "expire": ["终身"]
            },

        }
        for k in plan:

            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["interval"],plan[k]["expire"]):

                if v[3] == "0":

                    payType = "一次缴清"
                else:

                    payType = "年缴"

                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],payType,v[4]
                ))
                self.mysql._conn.commit()
                print(
                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], payType, v[4]
                    )
                )

    #执行爬虫
    def requestJson(self,dt=None):


        data = {

            "bbirthday": dt["year"],
            "jiaofeiqijian": "1000" if dt["interval"] == "0" else dt["interval"],
            "sex": "男" if dt["gender"] == "M" else "女"
        }

        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and r.json()["success"] == "true":

            num = int(dt["money"])/10000

            price = Helper.decimalParse(float(r.json()["value"]) * 10 * num)

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )

            print("/*更新产品价格失败:%d/*"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )
